<template>
  <nav-back title="登录/注册" />
  <van-form ref="formBox" @submit="submit">
    <van-cell-group inset>
      <van-field
        center
        label="手机号"
        label-width="50px"
        name="phone"
        v-model="state.ruleForm.phone"
        :rules="[
          { required: true, message: '手机号为必填项哦~' },
          {
            pattern: /^(?:(?:\+|00)86)?1\d{10}$/,
            message: '手机号格式不对哦~',
          },
        ]"
      >
        <template #button>
          <van-button
            class="form-btn"
            size="small"
            type="primary"
            @click="send"
            :disabled="state.button.disable"
          >
            {{ state.button.text }}
          </van-button>
        </template>
      </van-field>

      <van-field
        label="验证码"
        label-width="50px"
        v-model="state.ruleForm.code"
        :rules="[
          { required: true, message: '验证码为必填项哦~' },
          { pattern: /^\d{6}$/, message: '验证码必须是6位数字哦~' },
        ]"
      />
    </van-cell-group>

    <div style="margin: 20px 40px">
      <van-button
        round
        block
        type="primary"
        native-type="submit"
        loading-text="小主,奴家正努力处理中..."
      >
        立即登录/注册
      </van-button>
    </div>
  </van-form>
</template>

<script setup>
import NavBack from "@/components/NavBack.vue";
import { reactive, ref, onBeforeUnmount } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useStore } from "vuex";
import { Toast } from "vant";
import api from "@/api";

const router = useRouter(),
  store = useStore(),
  route = useRoute();

// 构建响应式数据
const state = reactive({
  ruleForm: {
    phone: "",
    code: "",
  },
  button: {
    disable: false,
    text: "发送验证码",
  },
});

// 获取van-form实例
const formBox = ref(null);

// 发送验证码
let timer = null;
const send = async () => {
  try {
    // 单独对手机号进行格式校验
    await formBox.value.validate("phone");
    // 格式校验成功:发送验证码
    let { code } = await api.phoneCode(state.ruleForm.phone);
    if (+code !== 0) {
      Toast("发送验证码失败,请稍后再试!");
      return;
    }
    // 验证码发送成功:按钮置灰&&开启倒计时
    let num = 30;
    state.button.disable = true;
    state.button.text = num + "秒";
    timer = setInterval(() => {
      num--;
      if (num <= 0) {
        clearInterval(timer);
        state.button.disable = false;
        state.button.text = "重新发送";
        return;
      }
      state.button.text = `${num < 10 ? "0" + num : num}秒`;
    }, 1000);
  } catch (_) {}
};
onBeforeUnmount(() => clearInterval(timer));

// 表单提交
const submit = async () => {
  // 进入到这里说明表单校验已经通过「按钮：native-type="submit"」
  try {
    let { code, token } = await api.login(state.ruleForm);
    if (+code !== 0) {
      Toast.fail("登录失败了~~");
      return;
    }
    // 登录成功:把token存储到本地 && 返回上级路由 && 修改vuex中的值(同步修改isLogin为true；异步获取登录者信息；)
    Toast.success("恭喜您登录成功了~~");
    localStorage.setItem("tk", token);
    store.commit("changeIsLogin", true);
    store.dispatch("changeInfoAsync");
    store.dispatch("queryStoreListAsync");
    // 如果URL中有传递to地址，则登录成功跳到这个地方;如果没有则从哪来回哪去;
    let { to } = route.query;
    to ? router.replace(to) : router.go(-1);
  } catch (_) {}
};
</script>

<style lang="less" scoped>
.van-form {
  margin-top: 30px;

  .form-btn {
    width: 78px;
  }
}
</style>